package com.wendu.oa.leave.service.leave.impl;

import com.wendu.oa.common.exception.BusinessException;
import com.wendu.oa.leave.common.LeaveStatusEnum;
import com.wendu.oa.leave.dao.leave.ApprevDao;
import com.wendu.oa.leave.dto.LeaveDto;
import com.wendu.oa.leave.model.Leave;
import com.wendu.oa.leave.service.leave.ApprevService;
import com.wendu.oa.service.page.PageUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service @Transactional
@CacheConfig(cacheNames = "service.leave")
public class ApprevServiceImpl implements ApprevService {

    @Resource
    private ApprevDao apprevDao;

    @Cacheable(key = "targetClass+'.'+methodName+'('+#p0+')'")
    @Override
    public Map<String,Object> getAppList(LeaveDto leaveDto) {
        return PageUtils.getPage(leaveDto,()->apprevDao.findAppList(leaveDto));
    }

    @CacheEvict(allEntries = true)
    @Override
    public void saveNewLeave(LeaveDto leaveDto) {

        leaveDto.setL_id(UUID.randomUUID().toString());
        //leaveDto.setL_status(0);//这里的0为硬编码

        leaveDto.setL_status(LeaveStatusEnum.UNCOMMITED.getCode());//可配置的灵活编码

        apprevDao.insertNewLeave(leaveDto);


    }

    @CacheEvict(allEntries = true)
    @Override
    public void commitLeave(LeaveDto leaveDto) {
        //是否为指定用户的请假条
        boolean ok = apprevDao.findExistsLeaveByEidAndLid(leaveDto);
        if(!ok){
            throw new BusinessException("不允许提交非当前用户的请假条！");
        }

        //是否为未提交的请假条
        boolean uncommited = apprevDao.findIsUncommitedLeave(leaveDto.getL_id());
        if(!uncommited){
            throw new BusinessException("不允许提交已提交的请假条！");
        }
        leaveDto.setL_date(new Date());
        apprevDao.updateStatusCommited(leaveDto);
    }
    @CacheEvict(allEntries = true)
    @Override
    public void revLeave(LeaveDto leaveDto) {
        //是否为指定用户的请假条
        boolean ok = apprevDao.findExistsLeaveByEidAndLid(leaveDto);
        if(!ok){
            throw new BusinessException("不允许对非当前用户的请假条销假！");
        }

        //是否为已审批通过的请假条
        boolean passed = apprevDao.findIspassedLeave(leaveDto.getL_id());
        if(!passed){
            throw new BusinessException("不允许对未审批通过的请假条销假！");
        }
        leaveDto.setL_date(new Date());
        apprevDao.updateStatusRev(leaveDto);
    }
}
